// Copyright (c) 2012, yuno. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
//    this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
//    this list of conditions and the following disclaimer in the documentation
//    and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of contributors
//    may be used to endorse or promote products derived from this software
//    without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
package sugarmintcandy.widgetwindow;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class DonationActivity extends Activity implements
	SharedPreferences.OnSharedPreferenceChangeListener,
	PurchaseStateListener, View.OnClickListener {
    private static final int STATE_INITIALIZATION_IN_PROGRESS = 1;
    private static final int STATE_INITIALIZATION_ERROR = 2;
    private static final int STATE_INITIALIZED = 3;
    private static final int STATE_TRANSACTION_IN_PROGRESS = 4;
    private static final int STATE_TRANSACTION_ERROR = 5;
    private static final int STATE_TRANSACTION_COMPLETED = 6;

    private static boolean sTransactionsRestored;

    private BillingService mBillingService;
    private SharedPreferences mPreferences;
    private int mPurchaseState;
    private int mResponseCode;
    private int mBillingState;

    private View mDonateButton;
    private View mRetryButton;
    private View mProgressBar;
    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.donation);
	setTitle(R.string.donation);
	ApiHelper.setDisplayHomeAsUpEnabled(this, true);

	mDonateButton = findViewById(R.id.donate_button);
	mRetryButton = findViewById(R.id.retry_button);
	mProgressBar = findViewById(R.id.progress_bar);
	mTextView = (TextView) findViewById(R.id.text_view);

	mDonateButton.setOnClickListener(this);
	mRetryButton.setOnClickListener(this);

	mPreferences = PreferenceManager.getDefaultSharedPreferences(this);
	mPreferences.registerOnSharedPreferenceChangeListener(this);
	mPurchaseState = mPreferences.getInt(PreferenceKeys.DONATION_STATE, 0);

	MainApplication app = (MainApplication) getApplication();
	mBillingService = app.getBillingService();
	mBillingService.registerPurchaseStateListener(this);
	if (mPurchaseState != BillingService.STATE_PURCHASED) {
	    doCheckBillingSupported();
	}

	updateViews();
    }

    @Override
    protected void onDestroy() {
	super.onDestroy();
	mPreferences.unregisterOnSharedPreferenceChangeListener(this);
	mBillingService.unregisterPurchaseStateListener(this);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	int id = item.getItemId();
	if (id == android.R.id.home) {
	    finish();
	    return true;
	}
	return super.onOptionsItemSelected(item);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
	    String key) {
	if (PreferenceKeys.DONATION_STATE.equals(key)) {
	    mPurchaseState = mPreferences.getInt(PreferenceKeys.DONATION_STATE,
		    0);
	    mResponseCode = BillingService.RESPONSE_OK;
	    updateViews();
	}
    }

    @Override
    public void onPurchaseStateChanged(String orderId, String productId,
	    int state) {
	Debug.trace("orderId=%s, productId=%s, state=%d", orderId, productId,
		state);
	if (Constants.PRODUCT_DONATION.equals(productId)) {
	    if (mBillingState >= STATE_TRANSACTION_IN_PROGRESS) {
		mBillingState = STATE_TRANSACTION_COMPLETED;
	    }
	    mPurchaseState = state;
	    mResponseCode = BillingService.RESPONSE_OK;
	    updateViews();
	}
    }

    @Override
    public void onClick(View v) {
	Debug.trace("mBillingState=" + mBillingState);
	if (mBillingState <= STATE_INITIALIZATION_ERROR) {
	    doCheckBillingSupported();
	} else {
	    doRequestPurchase();
	}
	updateViews();
    }

    private void updateViews() {
	Debug.trace("mPurchaseState=" + mPurchaseState + ", mResponseCode="
		+ mResponseCode + ", mBillingState=" + mBillingState);
	if (mPurchaseState == BillingService.STATE_PURCHASED) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.GONE);
	    mProgressBar.setVisibility(View.GONE);
	    if (mBillingState == STATE_TRANSACTION_COMPLETED) {
		mTextView.setText(R.string.donation_has_been_made);
	    } else {
		mTextView.setText(R.string.donation_was_made);
	    }
	    return;
	}
	if (mBillingState == STATE_INITIALIZATION_IN_PROGRESS) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.GONE);
	    mProgressBar.setVisibility(View.VISIBLE);
	    mTextView.setText(R.string.connecting);
	    return;
	}
	if (mBillingState == STATE_TRANSACTION_IN_PROGRESS) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.GONE);
	    mProgressBar.setVisibility(View.VISIBLE);
	    mTextView.setText(R.string.transaction_in_progress);
	    return;
	}
	if (mResponseCode == BillingService.RESPONSE_DEVELOPER_ERROR) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.VISIBLE);
	    mProgressBar.setVisibility(View.GONE);
	    mTextView.setText(R.string.billing_developer_error);
	    return;
	}
	if (mResponseCode == BillingService.RESPONSE_BILLING_UNAVAILABLE) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.VISIBLE);
	    mProgressBar.setVisibility(View.GONE);
	    mTextView.setText(R.string.billing_unavailable);
	    return;
	}
	if (mBillingState <= STATE_INITIALIZATION_ERROR) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.VISIBLE);
	    mProgressBar.setVisibility(View.GONE);
	    mTextView.setText(R.string.billing_init_failed);
	    return;
	}
	if (mBillingState == STATE_TRANSACTION_COMPLETED
		&& mPurchaseState == BillingService.STATE_CANCELED
		|| mResponseCode == BillingService.RESPONSE_USER_CANCELED) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.VISIBLE);
	    mProgressBar.setVisibility(View.GONE);
	    mTextView.setText(R.string.transaction_canceled);
	    return;
	}
	if (mBillingState == STATE_TRANSACTION_ERROR) {
	    mDonateButton.setVisibility(View.GONE);
	    mRetryButton.setVisibility(View.VISIBLE);
	    mProgressBar.setVisibility(View.GONE);
	    mTextView.setText(R.string.transaction_failed);
	    return;
	}
	mDonateButton.setVisibility(View.VISIBLE);
	mRetryButton.setVisibility(View.GONE);
	mProgressBar.setVisibility(View.GONE);
	mTextView.setText(R.string.please_donate);
    }

    private void doCheckBillingSupported() {
	mBillingState = STATE_INITIALIZATION_IN_PROGRESS;
	mBillingService.checkBillingSupported(new BillingResponseHandler() {
	    @Override
	    public void onBillingResponse(int responseCode) {
		if (responseCode == BillingService.RESPONSE_OK) {
		    if (!sTransactionsRestored) {
			doRestoreTransactions();
		    } else {
			mBillingState = STATE_INITIALIZED;
		    }
		} else {
		    mBillingState = STATE_INITIALIZATION_ERROR;
		}
		mResponseCode = responseCode;
		updateViews();
	    }
	});
    }

    private void doRestoreTransactions() {
	mBillingService.restoreTransactions(new BillingResponseHandler() {
	    @Override
	    public void onBillingResponse(int responseCode) {
		if (responseCode == BillingService.RESPONSE_OK) {
		    mBillingState = STATE_INITIALIZED;
		    sTransactionsRestored = true;
		} else {
		    mBillingState = STATE_INITIALIZATION_ERROR;
		}
		mResponseCode = responseCode;
		updateViews();
	    }
	});
    }

    private void doRequestPurchase() {
	mBillingState = STATE_TRANSACTION_IN_PROGRESS;
	mBillingService.requestPurchase(this, Constants.PRODUCT_DONATION,
		new BillingResponseHandler() {
		    @Override
		    public void onBillingResponse(int responseCode) {
			if (responseCode != BillingService.RESPONSE_OK) {
			    mBillingState = STATE_TRANSACTION_ERROR;
			}
			mResponseCode = responseCode;
			updateViews();
		    }
		});
    }
}
